package com.xiaoqiang.git.hellojavaserialportnew.config;

import com.xiaoqiang.git.hellojavaserialportnew.model.Reply;
import jssc.*;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.ConcurrentHashMap;

@Configuration
public class SerialConfig {

    // 串口连接
    private static ConcurrentHashMap<String,SerialPort> SERIAL_PORT = new ConcurrentHashMap<>();

    /**
     * 串口连接
     * @param portName
     * @param baudRate
     * @return
     */
    public static Reply openSerialPort(String portName, int baudRate){
        try {
            final SerialPort serialPort =new SerialPort(portName);//串口号;
            serialPort.openPort();
            serialPort.setParams(baudRate,8,1,0);
            if(serialPort.isOpened()) {
                System.out.println("打开串口：" + serialPort.getPortName());
            }

            // 串口数据监控
            serialPort.addEventListener(new SerialPortEventListener() {

                public void serialEvent(SerialPortEvent serialPortEvent) {
                    if (serialPortEvent.isRXCHAR()) {
                        try {
                            if (serialPortEvent.getEventValue() >0) {
                                byte[] bytes =serialPort.readBytes(serialPortEvent.getEventValue());
                                //以16进制的方式读取串口返回数据
                                System.out.println("串口：" + portName +"，接收数据：" +serialPort.readHexString(serialPortEvent.getEventValue()));
                            }
                            Thread.sleep(50);
                        }catch (Exception e) {
                            e.printStackTrace();
                        }

                    }
                }
            });

            SERIAL_PORT.put(portName,serialPort);
            return Reply.success();
        }catch (Exception e){
            return Reply.fail(e,"连接异常");
        }
    }

    public static Reply closeSerialPort(String portName){
        SerialPort serialPort = SERIAL_PORT.get(portName);
        if(serialPort != null) {
            try {
                serialPort.closePort();
            } catch (Exception e) {

            }
        }
        return Reply.success();
    }

    /**
     * 发送串口命令
     * @param portName
     * @param message
     */
    public static Reply sendData(String portName,String message) {
        SerialPort serialPort = SERIAL_PORT.get(portName);
        if(serialPort == null)return Reply.fail("-1","串口不存在或未连接");
        byte[] bytes = message.getBytes();
        if (serialPort.isOpened()) {

            try{

                serialPort.writeBytes(bytes);

                System.out.print("---发送数据：");

                for(byte item : bytes) {

                    System.out.print(item +" ");

                }

                System.out.println("---");
                return Reply.success();
            }catch (SerialPortException e) {
                SERIAL_PORT.remove(portName);
                try {
                    serialPort.closePort();
                }catch (Exception e1){

                }
                e.printStackTrace();
                return Reply.fail(e,"异常");
            }
        }
        return Reply.fail("-1","串口未连接");
    }



    /**
     * 获取串口列表
     * @return
     */
    public static String[] getSerials(){
        return SerialPortList.getPortNames();
    }

}
